import React, { useState, useEffect } from 'react';
import { Spin } from 'antd';

interface ModelInfo {
  name: string;
  status: 'online' | 'offline' | 'loading';
  version?: string;
  lastChecked?: Date;
}

const StatusBar: React.FC = () => {
  const [modelInfo, setModelInfo] = useState<ModelInfo>({
    name: '未知模型',
    status: 'loading'
  });

  // 检查AI服务器状态
  const checkAIServerStatus = async () => {
    try {
      // 使用AbortController实现超时
      const controller = new AbortController();
      const timeoutId = setTimeout(() => controller.abort(), 5000);
      
      let response;
      let serverUrl = 'http://118.145.200.164:5080';
      
      try {
        // 首先尝试健康检查端点
        response = await fetch(`${serverUrl}/api/v1/health`, {
          method: 'GET',
          signal: controller.signal,
        });
      } catch (healthError) {
        // 如果健康检查失败，尝试检测推理端点是否可达
        console.log('健康检查端点不可用，尝试推理端点...');
        response = await fetch(`${serverUrl}/api/v1/check-image`, {
          method: 'POST',
          signal: controller.signal,
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({ image_url: 'test', user_id: 'health_check' })
        });
      }

      clearTimeout(timeoutId);

      if (response && response.status !== 0) {
        // 服务器响应了（即使可能是错误响应），说明服务器在运行
        let data: any = {};
        try {
          data = await response.json();
        } catch (e) {
          // JSON解析失败，但服务器在运行
        }
        
        setModelInfo({
          name: data?.model || 'Ollama/Gemma3:4B',
          status: 'online',
          version: data?.version,
          lastChecked: new Date()
        });
      } else {
        setModelInfo(prev => ({
          ...prev,
          status: 'offline',
          lastChecked: new Date()
        }));
      }
    } catch (error) {
      console.log('AI服务器连接失败:', error);
      setModelInfo(prev => ({
        ...prev,
        status: 'offline',
        lastChecked: new Date()
      }));
    }
  };

  // 组件挂载时检查状态，然后每30秒检查一次
  useEffect(() => {
    checkAIServerStatus();
    const interval = setInterval(checkAIServerStatus, 30000);
    return () => clearInterval(interval);
  }, []);

  // 手动刷新状态
  const handleRefresh = () => {
    setModelInfo(prev => ({ ...prev, status: 'loading' }));
    checkAIServerStatus();
  };

  const getStatusColor = (status: string) => {
    switch (status) {
      case 'online': return '#52c41a'; // 绿色
      case 'offline': return '#ff4d4f'; // 红色
      case 'loading': return '#faad14'; // 橙色
      default: return '#d9d9d9'; // 灰色
    }
  };

  const getStatusText = (status: string) => {
    switch (status) {
      case 'online': return '正常';
      case 'offline': return '离线';
      case 'loading': return '检测中';
      default: return '未知';
    }
  };

  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
      <span>当前模型：{modelInfo.name}</span>
      <span>&nbsp;状态：</span>
      <span 
        style={{ 
          color: getStatusColor(modelInfo.status), 
          fontWeight: 600,
          cursor: 'pointer'
        }}
        onClick={handleRefresh}
        title={`点击刷新状态\n最后检查: ${modelInfo.lastChecked?.toLocaleString() || '未检查'}`}
      >
        {modelInfo.status === 'loading' ? <Spin size="small" style={{ color: getStatusColor(modelInfo.status) }} /> : '●'}
      </span>
      <span style={{ color: getStatusColor(modelInfo.status) }}>
        {getStatusText(modelInfo.status)}
      </span>
      {modelInfo.version && (
        <span style={{ color: '#8c8c8c', fontSize: '12px' }}>
          (v{modelInfo.version})
        </span>
      )}
    </div>
  );
};

export default StatusBar;
